#include "client.h"

Client::Client(QObject* parent)
	: QObject(parent)
{
	socket = new QTcpSocket(this);
	connectFlag = false;
	ConnectToServer();
}

Client::~Client()
{
	//回收内存
	socket->close();
	socket->deleteLater();
}

void Client::ConnectToServer()
{
	printf("Start connect to server");
	//ui->text_info->setPlainText(QString("cmd: %1").arg(ui->btn_connect->text()));
	if (!connectFlag)
	{
		QString ip = "127.0.0.1";	//获取ip
		int port = 1122;			//获取端口数据
		//取消已有的连接
		socket->abort();
		//连接服务器
		socket->connectToHost(ip, port);
		bool isconnect = socket->waitForConnected();//等待直到连接成功
		//如果连接成功
		if (isconnect)
		{
			connectFlag = true;
			//接收缓冲区（服务器）信息
			connect(socket, &QTcpSocket::readyRead, this, &Client::ReadData);
			printf("succeed!");
		}
		else
		{
			ConnectToServer();
			printf("failed!");
		}
	}
}

void Client::ReadData()
{
	QByteArray buf = socket->readAll();	// 读取数据

	QString data = QString(buf);
	if (!data.trimmed().isEmpty())
		emit SendWndData(data);		// 发送数据给前端
}
//发送按钮事件
bool Client::UavSendData(QString datastr)
{
    if (!connectFlag)return false;
	QByteArray data = datastr.toUtf8();//获取lineEdit控件中的数据并发送给服务器
	socket->write(data);
	//判断是否写入成功
	bool iswrite = socket->waitForBytesWritten();

    return iswrite;
}

void  Client::Reconnect() {
	connectFlag = false;
	ConnectToServer();
}
